﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Downloader
{
    public partial class DownloadForm : Form
    {
        private DownloadCore.DownloadManager downloadManager;

        public DownloadForm()
        {
            InitializeComponent();
        }
        private void ShowLog(string log)
        {
            this.rtbLog.Invoke(new Action(() =>
            {
                this.rtbLog.Text = string.Format("{0}\r\n{1}", log,this.rtbLog.Text);
            }));
        }
        private void btnCreateTask_Click(object sender, EventArgs e)
        {

            var downloadInfo = new DownloadCore.DownloadInfo();
            downloadInfo.saveDir = tbDir.Text;
            downloadInfo.downloadUrlList = new List<string> {
                tbUrl.Text
            };
            downloadInfo.taskCount = 5;
            downloadManager = new DownloadCore.DownloadManager(downloadInfo);
            downloadManager.OnDownload += DownloadManager_OnDownload;
            downloadManager.OnStart += DownloadManager_OnStart;
            downloadManager.OnStop += DownloadManager_OnStop;
            downloadManager.OnFinish += DownloadManager_OnFinish;

            ShowLog("新建任务");
        }

        private void DownloadManager_OnStop()
        {
            ShowLog("暂停下载");
        }

        private void DownloadManager_OnFinish()
        {
            ShowLog("完成下载");
        }

        private void DownloadManager_OnStart()
        {
            ShowLog("开始下载");
        }

        private void DownloadManager_OnDownload(long arg1, long arg2)
        {

            this.lbProcess.Invoke(new Action(() =>
            {
                
                this.pgbProcess.Value = (int)(arg1 * 100.00 / arg2);
                this.lbProcess.Text = string.Format("{0}/{1}", arg1, arg2);
            }));
        }

        private void btnStartDownload_Click(object sender, EventArgs e)
        {
            if (downloadManager == null) btnCreateTask_Click(null, null);
            downloadManager.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            downloadManager.Stop();
        }

        private void btnReStart_Click(object sender, EventArgs e)
        {
            if (downloadManager == null) btnCreateTask_Click(null, null);
            downloadManager.ReStart();
        }
    }
}
